<template>
  <el-card class="form-container" shadow="never">
    <el-form
      :model="course"
      :rules="rules"
      ref="courseFrom"
      label-width="120px"
      size="small"
    >
      <el-form-item label="专题名称：" prop="name">
        <el-input v-model="course.name" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="排序设置：" prop="sort">
        <el-input
          v-model="course.sort"
          type="number"
          class="input-width"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否考试：" prop="radio">
        <el-radio-group v-model="radio" style="margin-right: 20px">
          <el-radio label="是"></el-radio>
          <el-radio label="否"></el-radio>
        </el-radio-group>
        <el-date-picker
          v-if="radio == '是'"
          v-model="daterange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="dateRangeChange"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="开课时间：" prop="openTime">
        <el-date-picker
          v-model="course.openTime"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否签到/签退：" prop="sign">
        <el-table
          :data="signList"
          border
          size="mini"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column prop="checked" label="" width="40">
            <template slot-scope="scope">
              <el-checkbox
                v-model="signList[scope.$index].checked"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="signInStartTime" label="签到">
            <template slot-scope="scope">
              <el-date-picker
                style="width: 334px"
                v-model="signList[scope.$index].signInTime"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['12:00:00']"
              >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="signInEndTime" label="签退">
            <template slot-scope="scope">
              <el-date-picker
                style="width: 334px"
                v-model="signList[scope.$index].signOutTime"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['12:00:00']"
              >
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="50">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteRow(scope.$index, signList)"
                type="text"
                size="small"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button style="margin-top: 10px" @click="signAdd"
          >新增签到/签退</el-button
        >
      </el-form-item>
      <el-form-item label="专题封面：" prop="image">
        <single-upload v-model="course.image"></single-upload>
      </el-form-item>
      <el-form-item label="证书图片：" prop="image">
        <single-upload v-model="course.certificate"></single-upload>
      </el-form-item>
      <el-form-item label="专题简介：" prop="desc">
        <el-input
          class="input-width"
          type="textarea"
          :rows="5"
          placeholder="请输入简介"
          v-model="course.desc"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="配置人员：" prop="userListRadio">
        <el-radio-group v-model="userListRadio" @change="userListRadiChange">
          <el-radio label="所有用户"></el-radio>
          <el-radio label="指定用户"></el-radio>
        </el-radio-group>
      </el-form-item>
      <userList v-if="userListRadio === '指定用户'" ref="userList"></userList>
      <el-form-item style="margin-top: 20px">
        <el-button type="primary" @click="onSubmit('courseFrom')"
          >提交</el-button
        >
        <el-button @click="back">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import SingleUpload from '@/components/Upload/singleUpload'
import UserList from './userList'

import { collegeSpeSave, collegeSpeUpdate, collegeById } from '@/api/college'
import moment from 'moment'

const defaultCourse = {
  certificate: '',
  collegeId: 1,
  createTime: '',
  desc: '',
  endTime: '',
  examId: 0,
  image: '',
  name: '',
  startTime: '',
  status: '01',
  title: '',
  trainingStatus: '',
  signList: [],
  openTime: ''
}
export default {
  name: 'CourseDetail',
  components: { SingleUpload, UserList },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      daterange: [],
      userListRadio: '所有用户',
      radio: '是',
      course: Object.assign({}, defaultCourse),
      deptOptions: [],
      courseTypeOptions: [],
      priceTypeOptions: [],
      loading: false,
      rules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ],
        image: [{ required: true, message: '请选择封面', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入简介', trigger: 'blur' }]
      },
      signList: [],
      multipleSelection: []
    }
  },
  created () {
    setTimeout(() => {
      this.$refs['courseFrom'].resetFields()
    }, 0)
    if (this.isEdit) {
      collegeById({ id: this.$route.query.id }).then((response) => {
        this.course = response.data
        this.signList = response.data.signList.map((item) => {
          return {
            checked: !!item.checked,
            signInTime: [item.signInStartTime, item.signInEndTime],
            signOutTime: [item.signOutStartTime, item.signOutEndTime]
          }
        })
        if (response.data.userList.length > 0) {
          this.userListRadio = '指定用户'
          this.$nextTick(() => {
            this.$refs.userList.setUserList(response.data.userList)
          })
        }
        if (response.data.trainingStatus === '00') {
          this.radio = '否'
        }
        this.daterange = [response.data.startTime, response.data.endTime]
      })
    }
  },
  methods: {
    dateRangeChange (e) {
      this.course.startTime = moment(e[0]).format('YYYY-MM-DD')
      this.course.endTime = moment(e[1]).format('YYYY-MM-DD')
    },
    formatDate (time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    onSubmit (courseFrom) {
      let count = 0
      this.course.signList = this.signList.map((item) => {
        if (item.signInTime && item.signInTime.length > 0 && item.signOutTime && item.signOutTime.length > 0) {
          return { checked: item.checked ? 1 : 0, signInStartTime: this.formatDate(item.signInTime[0]), signInEndTime: this.formatDate(item.signInTime[1]), signOutStartTime: this.formatDate(item.signOutTime[0]), signOutEndTime: this.formatDate(item.signOutTime[1]) }
        } else {
          count++
        }
      })
      if (count > 0) {
        return this.$message({
          message: '请补全签到日期',
          type: 'error',
          duration: 1000
        })
      }
      if (this.userListRadio === '指定用户') {
        this.course.userList = this.$refs.userList.getUserList()
        if (this.course.userList.length === 0) {
          return this.$message({
            message: '请选择配置人员',
            type: 'error',
            duration: 1000
          })
        }
      }

      if (this.course.openTime) {
        this.course.openTime = this.formatDate(this.course.openTime)
      }
      this.course.updateTime = ''
      this.course.createTime = ''
      this.$refs['courseFrom'].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.isEdit) {
              this.course.collegeId = 1
              if (this.radio === '否') {
                this.course.trainingStatus = '00'
                this.course.startTime = null
                this.course.endTime = null
              }
              // console.log(this.course);
              this.course.id = this.$route.query.id
              const data = {
                ...this.course
              }
              if (this.userListRadio === '所有用户') {
                data.userList = []
              }

              collegeSpeUpdate(data).then((response) => {
                // this.$refs[formName].resetFields()
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 1000
                })
                this.$router.back()
              })
            } else {
              collegeSpeSave(this.course).then((response) => {
                this.$message({
                  message: '提交成功',
                  type: 'success',
                  duration: 1000
                })
                this.$router.back()
              })
            }

          })
        } else {
          this.$message({
            message: '提交失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    resetForm (courseFrom) {
      this.$refs[courseFrom].resetFields()
      this.course = Object.assign({}, defaultCourse)
    },
    back () {
      this.$router.go(-1)
    },
    signAdd () {
      this.signList.push({
        signInTime: [],
        signOutTime: []
      })
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    userListRadiChange () {
      if (this.userListRadio === '指定用户') {
        this.$refs.userList.setUserList(this.course.userList)
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.input-width {
  width: 70%;
}
.form-container {
  width: 1020px;
}
.w160 {
  width: 176px;
}
</style>
